package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author GaoYiJie
 * @Description
 * @Create 2025/4/17 9:43
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        //判断用户是否存在
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getPhone, loginInfoVo.getPhone()));

        if (user == null){
            return R.ERROR(500,"用户不存在");
        }

        if (!loginInfoVo.getPassword().equals(user.getPassword())){
            return R.ERROR(500,"密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getId())
                .claim("phone", user.getPhone())
                .compact();
        String tokenKey = "login_token:"+user.getId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,15, TimeUnit.MINUTES);

        user.setToken(token);
        user.setPassword(null);

        return R.OK(user);
    }
}
